<template>
  <div class="simple-form">
    <!--    :rules="props.rules || rules"-->
    <a-form
        ref="formRef"
        :label-col="labelCol"
        :model="MyForm.formDatas"
        :wrapper-col="wrapperCol"
        hideRequiredMark
        labelAlign="left"
        @finish="handleFinish"
        @finishFailed="handleFinishFailed"
    >
      <a-form-item v-for="(item ,index) in MyForm.datas" :key="item.name"
                   ref="name" :label="item.title" :name="item.name"
                   :rules="[{ required: true, message: `请输入${item.title}` }]"
      >
        <template v-if="item.type === 'input'">
          <a-input
              v-model:value="MyForm.formDatas[item.name]"
              :placeholder="item.hint || `请输入${item.title}`" :type="item.inputType || ''"
          />
        </template>
        <template v-if="item.type === 'number'">
          <a-input-number v-model:value="MyForm.formDatas[item.name]" :min="1" class="numberInput"/>
        </template>
        <template v-if="item.type === 'select'">
          <a-select
              v-model:value="MyForm.formDatas[item.name]"
              :mode="item.mode"
              :placeholder="item.hint || `请选择`"
              :size="MyForm.size"
              allow-clear
          >
            <a-select-option
                v-for="selection in item.items"
                :key="selection.id"
                :value="selection.id"
            >
              {{ selection.name }}
            </a-select-option>
          </a-select>
        </template>
      </a-form-item>
    </a-form>
  </div>
  <div class="btnBox flex-center">
    <BtnGroup @close="$emit('close')" @submit="submit"></BtnGroup>
  </div>
</template>

<script setup>
import {inject} from "@vue/runtime-core";
import BtnGroup from "@/components/customs/btn-group/index";
import {ref} from "@vue/reactivity";
import {Api} from "@/common/api";
import {requestMethod} from "@/common/request";
import {message} from "ant-design-vue";

const labelCol = {span: 3};
const wrapperCol = {span: 21};
const MyForm = inject("MyForm");
const formRef = ref();
const props = defineProps({
  rules: {
    type: Array,
    default: []
  }
});
let validatePass = async (_rule, value) => {
  if ("id" in MyForm.formDatas) {
    return Promise.resolve();
  } else if (value === "" || !value) {
    return Promise.reject("输入密码");
  } else {
    // if (MyForm.formData.rePassword !== "" && 'rePassword' in MyForm.formData) {
    //  formRef.value.validateFields("rePassword");
    // }
    return Promise.resolve();
  }
};
let validatePass2 = async (_rule, value) => {
  console.log(MyForm.formDatas, "---", _rule, value, (value === "" || !value), !("id" in MyForm.formDatas));
  if ((value === "" || !value) && !("id" in MyForm.formDatas)) {
    return Promise.reject("再次输入密码");
  } else if (value !== MyForm.formDatas.password) {
    return Promise.reject("密码不一致!");
  } else {
    return Promise.resolve();
  }
};
const rules = {
  name: [{
    required: true,
    message: "请输入",
    trigger: "change",
  }],
  username: [{
    required: true,
    message: "请输入",
    trigger: "change",
  }],
  mobile: [{
    required: true,
    message: "请输入",
    trigger: "change",
  }],
  password: [{
    validator: validatePass,
    trigger: "change",
  }],
  rePassword: [{
    validator: validatePass2,
    trigger: "change",
  }],
  roles_id: [{
    required: true,
    message: "请选择",
    trigger: "change",
  }]
};
const emit = defineEmits(["submit", "close"]);
const handleFinish = (values) => {
  console.log(values, MyForm.formDatas);
};
const handleFinishFailed = errors => {
  console.log(errors);
};

const editSend =async () => {
  class SubmitApi extends Api{
    constructor() {
      super(`api/${MyForm.url}edit`);
      this.method(requestMethod.POST);
    }
  }
  const api = new SubmitApi
  api.data(MyForm.formDatas)
  await api.send()
  const {msg,code} = await api.getDatas()
  if (code === 0){
    message.success('修改成功')
    emit('close')
  }else{
    message.warn(msg)
  }
};

const addSend =async () => {
  class SubmitApi extends Api{
    constructor() {
      super(`api/index-${MyForm.url}cj`);
      this.method(requestMethod.POST);
    }
  }
  const api = new SubmitApi
  api.data(MyForm.formDatas)
  await api.send()
  const {msg,code} = await api.getDatas()
  if (code === 0){
    message.success('新建成功')
    emit('close')
  }else{
    message.warn(msg)
  }
};
const submit = () => {
  formRef.value.validate().then(() => {
    console.log("values", MyForm.formDatas);
    if (MyForm.formDatas.id){
      editSend()
    }else{
      addSend()
    }
  }).catch(error => {
    console.log("error", error, MyForm.formDatas);
  });
};
</script>

<style lang="less" scoped>
@import "./index.less";
</style>
